from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.http import HttpResponse  # 新增导入
from django.utils import timezone
import logging
from .forms import CustomLoginForm
from django.contrib.auth import logout

logger = logging.getLogger(__name__)

def user_login(request):
    if request.method == 'POST':
        form = CustomLoginForm(data=request.POST)
        # 登录失败时记录日志
        if not form.is_valid():
            username = request.POST.get('username', '未知用户名')
            password = request.POST.get('password', '未知用户名')
            ip_address = request.META.get('REMOTE_ADDR', 'unknown')
            logger.warning(
                f"登录失败 - 用户名: {username}, "
                f"登录失败 - 密码: {password}, "
                f"时间: {timezone.now()}, "
                f"IP地址: {ip_address}, "
                f"错误信息: {form.errors}"
            )
        # 登录成功的逻辑
        elif form.is_valid():
            user = form.get_user()
            login(request, user)
            if user.user_type == 'admin':
                return redirect('admin_dashboard')
            elif user.user_type == 'teacher':
                return redirect('teacher_dashboard')
            elif user.user_type == 'student':
                return redirect('student_dashboard')
    else:
        form = CustomLoginForm()
    return render(request, 'user/login.html', {'form': form})

def admin_dashboard(request):
    return render(request, 'admin/admin_dashboard.html')

def teacher_dashboard(request):
    return render(request, 'teacher/dashboard.html')

def student_dashboard(request):
    return render(request, 'student/student_dashboard.html')

def user_logout(request):
    logout(request)  # 清除用户会话
    return redirect('user_login')  # 登出后重定向到登录页